import psutil
import subprocess
import time
import os
import pathlib
from dotenv import load_dotenv
from log_utils import setup_loggers  # 导入新的日志模块

import logging
from status_monitor import setup_status_logger

# 配置日志
log_folder = os.path.join(str(pathlib.Path(__file__).parent.resolve()), "logs")
if not os.path.exists(log_folder):
    os.makedirs(log_folder)

# 创建不同的日志处理器
# 定义日志文件名列表和对应的日志级别
log_configs = [
    ("process_monitor.log", logging.INFO),
    ("status_monitor.log", logging.INFO),
    ("error_monitor.log", logging.ERROR)
]

# 替换原有的日志配置代码
loggers = setup_loggers()
process_logger = loggers['process']
status_logger = loggers['status']
error_logger = loggers['error']

# 添加缺失的日志处理器定义
process_log = logging.FileHandler(os.path.join(log_folder, "process_monitor.log"), encoding='utf-8')
status_log = logging.FileHandler(os.path.join(log_folder, "status_monitor.log"), encoding='utf-8')
error_log = logging.FileHandler(os.path.join(log_folder, "error_monitor.log"), encoding='utf-8')

# 设置日志级别和格式
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
process_log.setLevel(logging.INFO)
status_log.setLevel(logging.INFO)
error_log.setLevel(logging.ERROR)
process_log.setFormatter(formatter)
status_log.setFormatter(formatter)
error_log.setFormatter(formatter)

process_logger.addHandler(process_log)
status_logger.addHandler(status_log)
error_logger.addHandler(error_log)


# 加载环境变量（与原服务脚本保持一致）
PROJECT_ROOT = str(pathlib.Path(__file__).parent.resolve())
os.chdir(PROJECT_ROOT)
load_dotenv(os.path.join(PROJECT_ROOT, ".env"))

# 配置参数
PYTHON_PATH = os.path.join(PROJECT_ROOT, "venv", "Scripts", "python.exe")  # 虚拟环境Python路径
GUI_SCRIPT_PATH = os.path.join(PROJECT_ROOT, "web", "app", "UI", "gui.py")  # gui.py路径
CHECK_INTERVAL = 10  # 检查间隔（秒）

def normalize_path(path):
    """将路径转换为标准格式并统一为小写"""
    return os.path.normcase(os.path.normpath(path))

PYTHON_PATH = normalize_path(PYTHON_PATH)
GUI_SCRIPT_PATH = normalize_path(GUI_SCRIPT_PATH)

def is_gui_running():
    """检查 gui.py 进程是否运行"""
    for proc in psutil.process_iter(['pid', 'cmdline']):
        try:
            cmdline = proc.info['cmdline']
            if cmdline and len(cmdline) >= 2:
                normalized_cmdline_0 = normalize_path(cmdline[0])
                normalized_cmdline_1 = normalize_path(cmdline[1])
                if normalized_cmdline_0 == PYTHON_PATH and normalized_cmdline_1 == GUI_SCRIPT_PATH:
                    return True
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            continue
    return False

def start_gui():
    """启动 gui.py 进程"""
    try:
        process = subprocess.Popen(
            [PYTHON_PATH, GUI_SCRIPT_PATH],
            cwd=PROJECT_ROOT,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True
        )
        logging.info(f"已启动 gui.py，进程ID: {process.pid}")
        return True
    except Exception as e:
        logging.error(f"启动 gui.py 失败: {str(e)}")
        return False

def stop_gui():
    """关闭 gui.py 进程"""
    for proc in psutil.process_iter(['pid', 'cmdline']):
        try:
            cmdline = proc.info['cmdline']
            process_logger.info(f"当前检查的进程命令行参数: {cmdline}")
            if cmdline and len(cmdline) >= 2:
                normalized_cmdline_0 = normalize_path(cmdline[0])
                normalized_cmdline_1 = normalize_path(cmdline[1])
                if normalized_cmdline_0 == PYTHON_PATH and normalized_cmdline_1 == GUI_SCRIPT_PATH:
                    proc.terminate()
                    _, still_alive = psutil.wait_procs([proc], timeout=5)
                    if still_alive:
                        proc.kill()
                    status_logger.info(f"已关闭 gui.py，进程ID: {proc.pid}")
                    return True
        except (psutil.NoSuchProcess, psutil.AccessDenied) as e:
            error_logger.error(f"进程访问错误: {str(e)}")
            continue
    status_logger.info("未找到运行中的 gui.py 进程")
    return False

def main():
    logging.info("开始监控 gui.py 进程...")
    while True:
        if not is_gui_running():
            logging.info("检测到 gui.py 未运行，尝试重启...")
            start_gui()
        time.sleep(CHECK_INTERVAL)  # 等待指定间隔后再次检查

if __name__ == '__main__':
    main()